import { useEffect, useMemo } from 'react'
import dayjs from 'dayjs'
import { Badge, Button, Modal, Tooltip } from 'antd'
import { DeleteOutlined } from '@ant-design/icons'

import { CusAgGrid, ICusAgGridProps } from '@/components/CusAgGrid'
import { UnifiedPagination } from '@/components/UnifiedPagination'
import { addAGCellTexty } from '@oBiz/components/addTexty'
import { getReadStatusName } from '../utils'
import { BatchAddOrigRouteDrawer } from './BatchAddOrigRouteDrawer'
import { Filter } from './Filter'
import { IOrigRouteListItem, TCellParams, TCol } from './interface'
import { useBoundStore } from './store'
import { useOrigRouteList } from './useOrigRouteList'
import { popupSlot } from './utils'
import styles from './styles.module.less'

const ActionCell = ({ value }: TCellParams<'originalRouteId'>) => {
  const delOrigRoute = useBoundStore(v => v.delOrigRoute)
  if (value == null) return
  return (
    <Tooltip title="删除">
      <Button
        type="link"
        danger
        icon={<DeleteOutlined />}
        onClick={() => {
          Modal.confirm({
            title: '确认要删除吗？',
            onOk: () => delOrigRoute(value),
          })
        }}
      />
    </Tooltip>
  )
}

const Cell = (p: TCellParams) => {
  const { field } = p.colDef || {}
  switch (field) {
    case 'status': {
      const { value, valueFormatted } = p as TCellParams<'status'>
      if (value == null) return
      return <Badge color={value === 1 ? 'green' : $CSS_VAR.statusDefault} text={valueFormatted || value} />
    }
    case 'originalRouteId': {
      return <ActionCell {...(p as TCellParams<'originalRouteId'>)} />
    }
    default: {
      return addAGCellTexty(p)
    }
  }
}

export const OrigRoute = () => {
  useOrigRouteList() // 放最顶部

  const gridRef = useBoundStore(v => v.gridRef)
  const loading = useBoundStore(v => v.request?.loading)
  const data = useBoundStore(v => v.request?.data)
  const page = useBoundStore(v => v.reqData.page)
  const size = useBoundStore(v => v.reqData.size)
  const setReqData = useBoundStore(v => v.setReqData)
  const getData = useBoundStore(v => v.getData)

  // 列配置
  const defaultColDef = useMemo<Partial<TCol>>(
    () => ({
      flex: 1,
      minWidth: 180,
      sortable: false,
      cellRenderer: Cell,
    }),
    [],
  )
  const columnDefs = useMemo(
    () => [
      {
        field: 'waybillNo',
        headerName: '运单号',
        flex: 0.01,
        minWidth: 130,
      } satisfies TCol<'waybillNo'>,
      {
        field: 'merchantServers',
        headerName: '服务商',
      } satisfies TCol<'merchantServers'>,
      {
        field: 'channelNo',
        headerName: '渠道单号',
      } satisfies TCol<'channelNo'>,
      {
        field: 'originalRoute',
        headerName: '原始路由',
        flex: 2.5,
        minWidth: 210 * 2,
        autoHeight: true,
        wrapText: true,
      } satisfies TCol<'originalRoute'>,
      {
        field: 'occurDate',
        headerName: '发生时间',
        flex: 0.01,
        minWidth: 166,
        valueFormatter: ({ value: v }) => (v ? dayjs(v).$formatSmart($F_YMDHms) : ''),
      } satisfies TCol<'occurDate'>,
      {
        field: 'collectDate',
        headerName: '采集时间',
        flex: 0.01,
        minWidth: 166,
        valueFormatter: ({ value: v }) => (v ? dayjs(v).$formatSmart($F_YMDHms) : ''),
      } satisfies TCol<'collectDate'>,
      {
        field: 'status',
        headerName: '状态',
        flex: 0.01,
        minWidth: 86,
        valueFormatter: ({ value }) => getReadStatusName(value) || '',
      } satisfies TCol<'status'>,
      {
        field: 'originalRouteId',
        headerName: '操作',
        flex: 0.01,
        width: 86,
        minWidth: 86,
        pinned: 'right',
      } satisfies TCol<'originalRouteId'>,
    ],
    [],
  )

  // 分页器
  const statusBar = useMemo<ICusAgGridProps['statusBar']>(() => {
    return {
      statusPanels: [
        {
          statusPanel: UnifiedPagination,
          statusPanelParams: UnifiedPagination.defineProps({
            current: page,
            pageSize: size,
            total: data?.total,
            onChange: (page, size) => {
              setReqData({ page, size })
              getData(true)
            },
          }),
        },
      ],
    }
  }, [data?.total, getData, page, setReqData, size])

  // 清理，保留筛选条件
  useEffect(
    () => () =>
      useBoundStore.setState({ ...useBoundStore.getInitialState(), reqData: useBoundStore.getState().reqData }, true),
    [],
  )

  return (
    <div className={styles.box}>
      <div className={styles.header}>
        <div className={styles.header_filter}>
          <Filter />
        </div>
        <div className={styles.header_action}>
          <Button
            type="primary"
            onClick={() =>
              BatchAddOrigRouteDrawer.open({
                onSuccess: () => {
                  setReqData({ page: 1 })
                  getData(true)
                },
              })
            }
          >
            添加原始路由
          </Button>
        </div>
      </div>
      <div className={styles.main}>
        <CusAgGrid<IOrigRouteListItem>
          ref={gridRef}
          loading={loading}
          rowData={data?.records}
          defaultColDef={defaultColDef}
          columnDefs={columnDefs}
          statusBar={statusBar}
        />
      </div>
      <popupSlot.Slot />
    </div>
  )
}
